<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />

    <title>loginProviders Fragment</title>
    <link href="../../static/css/cas.css" rel="stylesheet" th:remove="tag" />
</head>

<body>
<main class="container mt-3 mb-3">
    <div th:fragment="loginProviders" th:remove="tag" class="login-providers">
        <div th:if="${#bools.isFalse(delegatedAuthenticationDynamicProviderSelection)}">
            <script type="text/javascript">
                let providers = [];
            </script>
            <div th:if="${delegatedAuthenticationProviderConfigurations}">

                <h3 class="text-center mt-md-0 mt-4">
                    <i class="fas fa-user-shield"></i>
                    <span th:if="${delegatedAuthenticationProviderPrimary == null}"
                          th:utext="#{screen.welcome.label.loginwith}">External Identity Providers</span>
                </h3>

                <div class="card-title" th:if="${delegatedAuthenticationProviderPrimary != null}">
                    <div class="alert alert-info" role="alert">
                        <span th:utext="#{screen.welcome.label.navto(${delegatedAuthenticationProviderPrimary.name})}" />
                        <p>
                        <div role="progressbar" class="mdc-linear-progress mdc-linear-progress--indeterminate">
                            <div class="mdc-linear-progress__buffer">
                                <div class="mdc-linear-progress__buffer-bar"></div>
                                <div class="mdc-linear-progress__buffer-dots"></div>
                            </div>
                            <div class="mdc-linear-progress__bar mdc-linear-progress__primary-bar">
                                <span class="mdc-linear-progress__bar-inner"></span>
                            </div>
                            <div class="mdc-linear-progress__bar mdc-linear-progress__secondary-bar">
                                <span class="mdc-linear-progress__bar-inner"></span>
                            </div>
                        </div>

                        </p>
                    </div>
                </div>


                
                <div id="identityProvidersPanel"
                     class="d-flex justify-content-center flex-wrap"
                     th:style="'visibility:' + ${delegatedAuthenticationProviderPrimary != null ? 'hidden' : 'visible'}">

                   <ul class="list-unstyled d-flex flex-column m-0 flex-fill"
                       th:if="${#lists.size(delegatedAuthenticationProviderConfigurations) <= 10}">
                        <li class="p-1 login-provider-item"
                            th:each="entry: ${delegatedAuthenticationProviderConfigurations}"
                            th:switch="${entry.type}">

                            <form method="post" th:id="${'form' + entry.name}" th:action="@{/login}">
                                <button class="mdc-button mdc-button--raised me-2 btn btn-primary d-block w-100"
                                        name="submitButton"
                                        id="submitButton"
                                        type="submit"
                                        th:attr="autoRedirectType=${#strings.toLowerCase(entry.autoRedirectType)},redirectUrl=@{${entry.redirectUrl}}"
                                        th:title="${entry.name + ' ' + entry.type}"
                                        th:id="${entry.name}"
                                        th:classappend="'mdc-button-' + ${entry.type} + ${entry.cssClass}"
                                        accesskey="s">
                                    <span class="mdc-button__label">[[${#strings.defaultString(entry.title,entry.name)}]]</span>
                                </button>

                                <input type="hidden" name="client_name" th:value="${entry.name}" />
                                <input type="hidden" name="_eventId" value="delegatedAuthenticationRedirect" />
                                <input type="hidden" name="execution" th:value="${flowExecutionKey}" />
                            </form>

                            <script th:inline="javascript">
                                /*<![CDATA[*/
                                providers.push({
                                    name: /*[[${entry.name}]]*/ ,
                                    type: /*[[${entry.type}]]*/ ,
                                    url: /*[[@{${entry.redirectUrl}}]]*/
                                });

                                document.addEventListener("DOMContentLoaded", (event) => {
                                    $("#fm1 #username").on("focusout", () => {
                                        const user = $("#fm1 #username").val();
                                        /*
                                        if (user.endsWith("@example.org")) {
                                            let provider = providers.find(element => element.name === "ClientName");
                                            $("#passwordSection").hide();
                                            location.href = provider.url;
                                        }
                                        */
                                    });
                                });
                                /*]]>*/
                            </script>

                        </li>
                    </ul>
                    
                   <div class="w-100 mt-2">
                       <select id="identityProviderOptions"
                               th:if="${#lists.size(delegatedAuthenticationProviderConfigurations) > 10}"
                               class="d-flex flex-column m-0 flex-fill custom-select mw-100">
                           <option th:each="entry : ${delegatedAuthenticationProviderConfigurations}"
                                   th:title="${#strings.defaultString(entry.title,entry.name)}"
                                   th:id="${entry.name}"
                                   th:value="${entry.name}"
                                   th:text="${#strings.defaultString(entry.title,entry.name)}"/>
                       </select>
                   </div>

                    <div class="clearfix"></div>
                    
                    <div id="identityProviderDiscoveryPanel"
                         class="d-flex justify-content-center mt-4"
                         th:if="${identityProviderDiscoveryEnabled}">
                        <script type="text/javascript" th:inline="javascript">
                            /*<![CDATA[*/
                            let url = /*[[@{/idp/discovery}]]*/ ;

                            let returnUrl = /*[[${cas.server.name} + @{/idp/discovery/redirect}]]*/ ;

                            if (window.location.search) {
                                returnUrl += encodeURIComponent(window.location.search);
                            }
                            url += `?return=${returnUrl}`;

                            const link = $("<a>", {
                                href: url,
                                id: "saml2IdPDiscovery",
                                class: "mdc-button mdc-button--raised d-block"
                            }).append(
                                $("<i>", {
                                    class: "mdi mdi-shield",
                                    "aria-hidden": "true"
                                }),
                                $("<span>", {
                                    class: "mdc-button__label",
                                    text: "SAML2 Identity Provider Discovery"
                                })
                            );
                            $("#identityProviderDiscoveryPanel").append(link);
                            
                            /*]]>*/
                        </script>
                    </div>
                    
                </div>
            </div>

            <div th:if="${wsfedUrls}" id="list-providers"
                 th:class="${delegatedAuthenticationProviderPrimary == null ? 'card d-sm-none d-md-block bg-light' : ''}">

                <div class="card-body">
                    <h3 class="card-title" th:utext="#{screen.welcome.label.loginwith}"
                        th:if="${delegatedAuthenticationProviderPrimary == null}">Login with:</h3>
                    <div class="card-title" th:if="${delegatedAuthenticationProviderPrimary != null}">
                        <div class="alert alert-info">:information_source:
                            <span th:utext="#{screen.welcome.label.navto(${delegatedAuthenticationProviderPrimary.name})}" />
                        </div>
                    </div>

                    <div class="card-text"
                         th:style="'display:' + ${delegatedAuthenticationProviderPrimary != null ? 'none' : 'block'}">
                        <ul>
                            <li class="p-1 login-provider-item" th:each="entry: ${wsfedUrls}">
                                <a class="mdc-button mdc-button--raised w-100"
                                   th:href="@{${entry.redirectUrl}}"
                                   th:inline="text" onload=""
                                   th:attr="autoRedirectType=${#strings.toLowerCase(entry.autoRedirectType)}"
                                   th:title="${entry.name}">

                                    <i class="mdi mdi-microsoft-windows" aria-hidden="true"></i>
                                    <span class="mdc-button__label">[[${entry.name}]]</span>
                                </a>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>

            <script type="text/javascript" th:inline="javascript">
                /*<![CDATA[*/
                
                const identityProviderOptions = $('#identityProviderOptions');
                const options = identityProviderOptions.find('option');
                const sorted = options.sort((a, b) => $(a).text().localeCompare($(b).text()));
                identityProviderOptions.empty().append(sorted).prop("selectedIndex", 0);

                $(identityProviderOptions).on('change', function () {
                    const selectedValue = $(this).val();

                    const formAction = /*[[@{/login}]]*/;
                    const flowExecutionKey = /*[[${flowExecutionKey}]]*/;

                    const form = $('<form>', {
                        method: 'POST',
                        action: formAction
                    });

                    $('<input>', {
                        type: 'hidden',
                        name: 'client_name',
                        value: selectedValue
                    }).appendTo(form);
                    $('<input>', {
                        type: 'hidden',
                        name: '_eventId',
                        value: 'delegatedAuthenticationRedirect'
                    }).appendTo(form);
                    $('<input>', {
                        type: 'hidden',
                        name: 'execution',
                        value: flowExecutionKey
                    }).appendTo(form);

                    form.appendTo('body').submit();
                });


                let primaryUrl = /*[[${delegatedAuthenticationProviderPrimary?.redirectUrl}]]*/;
                let primaryName = /*[[${delegatedAuthenticationProviderPrimary?.name}]]*/;

                const redirectTo = $("button[autoRedirectType=client]").attr("id");
                if (primaryUrl != null) {
                    console.log(`Redirecting to primary identity provider ${primaryName} via URL ${primaryUrl}`)
                    let form = document.getElementById(`form${primaryName}`);
                    form.submit();
                }
                else if (redirectTo !== null && redirectTo !== undefined) {
                    console.log(`Redirecting to identity provider URL ${redirectTo}`)
                    let form = document.getElementById(`form${redirectTo}`);
                    form.submit();
                } else {
                    console.log("No identity provider is configured for auto redirection.");
                }
                /*]]>*/
            </script>
        </div>

    </div>
</main>
</body>

</html>
